import { Menu } from '@/types/user'
import router from '@/router'

// 加载views下面的所有页面
const modules = import.meta.glob('../views/*/*.vue')
console.log('---modules---', modules)

export const addRoutes = (menus: Menu[]) => {
  const routes: { path: string; meta: { name: string }; component: any }[] = []

  menus.forEach(item => {
    item.children.forEach(subitem => {
      const fullComponentPath = `../views/${subitem.component}.vue`
      // 生成路由规则
      const route = {
        path: `${item.path}/${subitem.path}`.substring(1),
        meta: subitem.meta,
        // component: () => import('@/views/Swiper/index.vue') // 写死可以
        // component: () => import(`@/views/${subitem.component}.vue`) // 动态拼接报错
        component: modules[fullComponentPath]
      }

      routes.push(route)
    })
  })

  console.log('---routes---', routes)

  /** 
  router.addRoute('myLayout', {
    path: 'swiper/list',
    meta: {
      title: '轮播图列表'
    },
    component: () => import('@/views/Swiper/index.vue')
  })
  */
  // 一个一个添加动态路由
  routes.forEach(route => {
    router.addRoute('myLayout', route)
  })
}
